<template>
  <div class="app-container">
    <Table
      ref="table"
      :columns="columns"
      :page-function="page"
      :save-all-function="saveAll"
    >
    </Table>
    <el-dialog
      title="属性"
      :visible.sync="propertyDialog"
      :before-close="propertyDialogClose"
    >
      <div v-for="property of properties" :key="property.id" style="margin-bottom: 10px">
        <span style="line-height: 32px">
          {{ property.name }}：
        </span>
        <el-popover
          v-for=" (pv,index) in property.propertyValues"
          :key="index"
          placement="top"
          width="200"
          trigger="hover"
          style="margin-right: 5px"
        >
          <el-upload
            class="avatar-uploader"
            :action="actionUrl + '?id=' + pv.id"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            @click.native="pvRow = pv"
          >
            <img
              v-if="pv.image !== null && pv.image !== undefined && pv.image.name "
              :src="baseImgUrl + pv.image.name" class="avatar" >
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-tag
            slot="reference"
            closable
            v-show="pv.id !== 0 && propertyDialog"
            :disable-transitions="false"
            @close="handleClose(pv)"
          >
            {{ pv.name }}
          </el-tag>
        </el-popover>
        <el-input
          v-show="inputVisible===property.id"
          v-model="propertyValue"
          class="input-new-tag"
          :autofocus="true"
          :ref="'saveTagInput'+property.id"
          size="small"
          @keyup.enter.native="handleInputConfirm(property)"
          @blur="handleInputConfirm(property)"
          style="width: 100px"
        >
        </el-input>
        <el-button v-if="inputVisible!==property.id" class="button-new-tag" size="small"
                   @click="showInput(property.id)">+
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="sku"
      :visible.sync="skuDialog"
      :before-close="skuDialogClose"
    >
      <el-button size="small" v-if="row" @click="generateSku">
        {{ row.skus !== undefined && row.skus[0] === undefined ? '生成sku' : '重新生成sku' }}
      </el-button>
      <el-table
        max-height="300"
        :data="row.skus"
      >
        <el-table-column
          v-for="(property,index) of properties"
          :key="property.id"
          :label="property.name"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.propertyValues[index]!==undefined">{{ scope.row.propertyValues[index].name }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { saveAll, page, generateSku } from '@/api/product'
import { saveAll as saveAllPropertyValue } from '@/api/propertyValue'
import { list as listCategory } from '@/api/category'
import Table from '@/components/Table/index'
import { commonList } from '@/utils/common'

export default {
  name: 'Product',
  components: { Table },
  data() {
    return {
      pvRow:{},
      skuDialog: false,
      propertyValue: '',
      properties: [],
      inputVisible: 0,
      propertyDialog: false,
      page: page,
      saveAll: saveAll,
      categories: [],
      row: {},
      skuRow: {},
      baseImgUrl: process.env.VUE_APP_BASE_API + '/file/get/',
      actionUrl: process.env.VUE_APP_BASE_API + '/product/uploadPropertyValueImage'
    }
  },
  computed: {
    columns() {
      return [
        {
          prop: 'id',
          label: '序号',
          width: '80',
          form: {
            key: 'id',
            label: 'id'
          }
        },
        {
          prop: 'name',
          label: '名称',
          width: '180',
          form: {
            key: 'name',
            label: '名称',
            type: 'input'
          }
        },
        {
          prop: 'category.name',
          label: '分类',
          width: '180',
          form: {
            key: 'categoryId',
            label: '分类',
            type: 'cascader',
            options: this.categories
          }
        },
        {
          label: '图片',
          width: '180',
          type: 'image',
          form: {
            key: 'image',
            label: '图片',
            type: 'image'
          }
        },
        {
          form: {
            key: 'skus'
          }
        },
        {
          form: {
            key: 'propertyValues'
          }
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: '200px'
        },
        {
          prop: 'updateTime',
          label: '更新时间',
          width: '200px'
        },
        {
          label: '操作',
          type: 'action',
          buttons: [
            {
              name: 'sku',
              size: 'small',
              click: (row) => {
                this.showSkuDialog(row)
              }
            },
            {
              name: '属性',
              size: 'small',
              click: (row) => {
                this.showPropertyDialog(row)
              }
            }
          ]
        }
      ]
    }
  },
  beforeMount() {
    this.listCategory()
  },
  methods: {
    handleAvatarSuccess(res) {
      this.pvRow.image = res.data
      this.$refs.table.page()
      this.$forceUpdate()
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    generateSku() {
      generateSku({ productId: this.row.id }).then((resp) => {
        const { data } = resp
        this.row.skus = data
        this.$message.success('生成成功')
      })
    },
    showInput(propertyId) {
      this.inputVisible = propertyId
      this.$nextTick(() => {
        this.$refs['saveTagInput' + propertyId][0].$refs.input.focus()
      })
    },
    handleClose(pv) {
      pv.deleted = 1
      pv.image = undefined
      saveAllPropertyValue({ data: JSON.stringify([pv]) }).then(() => {
        // 隐藏该标签
        pv.id = 0
        this.$forceUpdate()
      })

    },
    handleInputConfirm(property) {
      if (this.propertyValue) {
        let propertyValue = { name: this.propertyValue }
        property.propertyValues.push(propertyValue)
        saveAllPropertyValue({
          data: JSON.stringify([{
            name: this.propertyValue,
            productId: this.row.id,
            propertyId: property.id
          }])
        }).then(res => {
          propertyValue.id = res.data[0].id
          this.$refs.table.page()
        })
      }
      this.inputVisible = 0
      this.propertyValue = ''
    },
    propertyDialogClose() {
      this.propertyDialog = false
      this.inputVisible = false
    },
    skuDialogClose() {
      this.skuDialog = false
    },
    showSkuDialog(row) {
      this.skuDialog = true
      this.row = row
      this.properties = row.category.properties
    },
    showPropertyDialog(row) {
      this.propertyDialog = true
      this.row = row
      this.properties = row.category.properties
      for (let property of this.properties) {
        property.propertyValues = []
        for (let pv of this.row.propertyValues) {
          if (pv.propertyId === property.id) {
            property.propertyValues.push(pv)
          }
        }
      }
    },
    listCategory() {
      commonList(this.categories, listCategory, false)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader{
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  margin: 0;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
